import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_mode/flash.dart';
import 'package:flutter_mode/generated/l10n.dart';
import 'package:flutter_mode/home.dart';
import 'package:flutter_mode/more/more.dart';
import 'package:flutter_mode/other/entries.dart';
import 'package:flutter_mode/other/inherited_demo.dart';
import 'package:flutter_mode/other/other.dart';
import 'package:flutter_mode/wh/main_wh.dart';
import 'package:flutter_mode/zjw/main_zjw.dart';
import 'package:flutter_mode/zyj/redux/main_redux.dart';
import 'package:flutter_mode/zyj/ui/main_zyj.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:get_storage/get_storage.dart';
import 'package:redux/redux.dart';

import 'ui/localizations.dart';

void main() async {
  await GetStorage.init();

  runApp(_widgetForRoute(window.defaultRouteName));
}

Widget _widgetForRoute(String route) {
  switch (route) {
    case 'route1':
      return Center(
        child: Text(
          'Hello route1',
          textDirection: TextDirection.ltr,
        ),
      );
    case 'route2':
      return Center(
        child: Text("I'm route2", textDirection: TextDirection.ltr),
      );
    case 'wh':
      return Center(
        child: MyAppWH(),
      );
    case 'zjw':
      return Center(
        child: MyAppZJW(),
      );
    case 'zyj':
      return MyAppZYJ();
    case 'start':
    default:
      return AppInheritedWidget(
        AppDataManager(),
        child: MyApp(),
      );
  }
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  final store =
      Store<MainRedux>(appReducer, initialState: MainRedux(user: null));

  @override
  Widget build(BuildContext context) {
    /*return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );*/

    // TODO 启用Material风 需要使用MaterialApp，同理iOS风需要CupertinoApp。否则部分控件会出现错乱的情况
    // todo MaterialApp中 home 与 routes中的‘/’ 仅可以存在一个
//    Navigator.of(context).widget.createElement().visitChildElements((Element element){
//      getTypeName(element.widget.runtimeType)
//      element.size.width
//    });
//GestureDetector(child: Text("a"), onTap: (){},behavior: HitTestBehavior.translucent,);
//    GestureBinding.instance.gestureArena.sweep(pointer)
//    print(getTypeName(runtimeType));// import 'package:quiver/mirrors.dart'; flutter禁止使用反射

    return StoreProvider<MainRedux>(
      store: store,
      child: MaterialApp(
          title: 'flutter Test',
          theme: ThemeData(
            primarySwatch: Colors.red,
          ),
          darkTheme: ThemeData(
            primarySwatch: Colors.teal,
            brightness: Brightness.dark
          ),
          themeMode: ThemeMode.system,
          initialRoute: '/',
          routes: {
            '/': (context) => FlashPage(),
            'main': (context) => MainScreen()
          },
          navigatorObservers: [_CustomgatorObserver()],
          // 本地化配置，平台控件默认使用英文，这里设置为首选中午
          /*localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
        ],
        supportedLocales: [
          Locale('zh', 'CN'),
          Locale('en', 'US')
        ],*/
          localizationsDelegates: [
            S.delegate,
            MyCupertinoLocalizations.delegate,
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
          ],
          supportedLocales: S.delegate.supportedLocales,
          localeResolutionCallback:
              // S.delegate.resolution(fallback: new Locale("zh", "")),
              (local, sc) {
            return new Locale("zh", "");
          }),
    );
  }
}

class _CustomgatorObserver extends NavigatorObserver {
  @override
  void didPop(Route route, Route? previousRoute) {
    // TODO: implement didPop
    super.didPop(route, previousRoute);
  }

  @override
  void didPush(Route route, Route? previousRoute) {
    // TODO: implement didPush
    print('didPush()');

    super.didPush(route, previousRoute);
  }

  @override
  void didRemove(Route route, Route? previousRoute) {
    // TODO: implement didRemove
    super.didRemove(route, previousRoute);
  }

  @override
  void didReplace({Route? newRoute, Route? oldRoute}) {
    // TODO: implement didReplace
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
  }

  @override
  void didStartUserGesture(Route route, Route? previousRoute) {
    // TODO: implement didStartUserGesture
    super.didStartUserGesture(route, previousRoute);
  }

  @override
  void didStopUserGesture() {
    // TODO: implement didStopUserGesture
    super.didStopUserGesture();
  }
}

class MainScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _MainScreenState();
  }
}

class _MainScreenState extends State<MainScreen> {
  var _curIndex = 0;
  var _pageCtr = PageController(initialPage: 0, keepPage: true);

  @override
  Widget build(BuildContext context) {
    // todo Scaffold的使用： https://www.jianshu.com/p/c9cab083cd96

    var titles = ['UI', '功能', '更多', '成员'];

    return Scaffold(
      appBar: AppBar(
        title: Text(titles[_curIndex]),
//        automaticallyImplyLeading: false,
      ),
      drawer: Drawer(
        child: Image.network(
          'https://www.yimizi.xyz/wedding/image/only/10.webp',
          fit: BoxFit.fitHeight,
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        items: <BottomNavigationBarItem>[
          BottomNavigationBarItem(
              label: titles[0], icon: Icon(Icons.ac_unit)),
          BottomNavigationBarItem(
              label: titles[1], icon: Icon(Icons.child_friendly)),
          BottomNavigationBarItem(
              label: titles[2],
              icon: Icon(Icons.airline_seat_recline_normal)),
          BottomNavigationBarItem(
              label: titles[3], icon: Icon(Icons.settings)),
        ],
        currentIndex: _curIndex,
        // fixedColor: Colors.green,
        onTap: (index) => _tapBar(index),
      ),
      body: PageView(
        controller: _pageCtr,
        children: <Widget>[
          MyHomePage(),
          OtherPage(),
          MorePage(),
          DataTable(columns: <DataColumn>[
            DataColumn(label: Text('其他Demo')),
          ], rows: <DataRow>[
            DataRow(cells: <DataCell>[
              DataCell(Text('王海'),
                  onTap: () => Navigator.push(context,
                          MaterialPageRoute(builder: (context) {
                        return MyAppWH();
                      }))),
            ]),
            DataRow(cells: <DataCell>[
              DataCell(Text('张玉久'),
                  onTap: () => Navigator.push(context,
                          MaterialPageRoute(builder: (context) {
                        return MyAppZYJ();
                      }))),
            ]),
            DataRow(cells: <DataCell>[
              DataCell(Text('张俊文'),
                  onTap: () => Navigator.push(context,
                          MaterialPageRoute(builder: (context) {
                        return MyAppZJW();
                      }))),
            ]),
          ])
        ],
        physics: NeverScrollableScrollPhysics(),
      ),
    );
  }

  _tapBar(int index) {
    setState(() {
      _curIndex = index;
      _pageCtr.jumpToPage(index);
    });
  }
}
